<script setup>
import {onMounted, reactive, watch} from 'vue'
import {ref} from 'vue'
import {ElMessage} from "element-plus";
import {get, post, put, del} from '@/api/request'

const emit = defineEmits(['on-cancel', 'on-submit']);
const dispatchForm = reactive({
  name: '',
  schoolId: '',
  ids: [],
  departId: ''
})

// 定义props接收父组件传来的数据
const props = defineProps({
  trbanji:null,
  type: {
    type: String,
    default: 'student', // 默认为学生类型，可选值：student, teacher等
  }
})
// 添加表单验证规则
const rules = {
  'schoolId': [
    {required: true, message: '请选择现班级', trigger: 'change'},
  ],
  'departId': [
    {required: true, message: '请选择调整后的班级', trigger: 'change'}
  ]
}
const setTrbanji = (e) => {
  console.log(e)
}
onMounted(() => {
  console.log('组件挂载时 trbanji 数据:', props.trbanji)
})


// 用于表单验证的引用
const formRef = ref(null)

const generateData = () => {
  const data = []
  return data
}
const getData = async () => {
  let templateUrl = '';
  if (props.type === 'student') {
    templateUrl = '/api/system/uis/list';
  } else if (props.type === 'teacher') {
    templateUrl = '/api/system/uit/list';
  }
  const res = await post(templateUrl, {})
  data.value = res.rows
  console.log(res.rows)
}
getData()

const data = ref(generateData())
const value = ref([])

const filterMethod = (query, item) => {
  console.log(query, item)
  // return item.label.includes(query) || item.id.includes(query)
}

const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      const name={
        student:'学生',
        teacher:'老师'
      }
      if (dispatchForm.ids.length === 0) { // 使用正确的属性
        ElMessage.warning('请选择至少一名'+ name[props.type])
        return
      }

      try {
        let templateUrl = '';
        if (props.type === 'student') {
          templateUrl = '/api/system/uis/move';
        } else if (props.type === 'teacher') {
          templateUrl = '/api/system/uit/move';
        }
          await post(templateUrl, dispatchForm)
          ElMessage.success('操作成功')
        // 可以在这里重置表单
        resetForm()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败，请重试')
      }

    } else {
      return false
    }
  })
}

const resetForm = () => {
  dispatchForm.schoolId = ''
  dispatchForm.departId = ''
  dispatchForm.ids = []
  value.value = []
  emit('on-cancel');
}

// 添加方法接收父组件传来的学生数据
const studentData = ref([])

const setStudentData = (data) => {
  console.log('接收到的学生数据:', data)
  // 这里可以处理传入的数据
  // 例如：可以更新transfer组件的数据源等
}

// 暴露方法给父组件调用
defineExpose({
  setStudentData
})
</script>

<template>
  <el-form ref="formRef" :model="dispatchForm" :rules="rules" label-width="120px">
    <el-form-item label="现班级" prop="schoolId" >
      <el-cascader style="width: 100%"
                   v-model="dispatchForm.schoolId"
                   :options="trbanji"
                   :props="{ label: 'departName', value: 'id', children: 'childs' }"

                   placeholder="请选择班级"
      />
    </el-form-item>
    <el-form-item label="请选择" required>
      <el-transfer
          v-model="dispatchForm.ids"
          :titles="['全选','全选']"
          filterable
          :props="{
      key: 'id',
      label: 'name',
    }"
          filter-placeholder="请输入学生姓名或学号"
          :data="data"
      />
    </el-form-item>

    <el-form-item label="调整后的班级" prop="departId" >
      <el-cascader style="width: 100%"
                   v-model="dispatchForm.departId"
                   :options="trbanji"
                   :props="{ label: 'departName', value: 'id', children: 'childs' ,emitPath:false }"
                   placeholder="请选择班级"
      />
    </el-form-item>
  </el-form>
  <div class="text-right">
    <el-button type="primary" @click="submitForm">提交</el-button>
    <el-button @click="resetForm">取消</el-button>
  </div>
</template>

<style scoped>
</style>
